package utils

import (
	"archive/tar"
	"compress/gzip"
	"errors"
	"io"
	"os"
	"syscall"
)

/** 解压tar.gz文件 */
func DeCompress(tarFile string, dest string) error {
	srcFile, err := os.Open(tarFile)
	if err != nil {
		return err
	}
	defer srcFile.Close()
	gr, err := gzip.NewReader(srcFile)
	if err != nil {
		return err
	}
	defer gr.Close()
	tr := tar.NewReader(gr)
	for {
		hdr, err := tr.Next()
		if err != nil {
			if err == io.EOF {
				break
			} else {
				return err
			}
		}
		filename := dest + "/" + hdr.Name
		file, err := createFile(filename)
		if err != nil {
			return err
		}
		io.Copy(file, tr)
	}
	return nil
}

/** 解压tar文件 */
func DeCompressTar(tarFile string, dest string) error {
	attr := &os.ProcAttr{
		Dir: dest,
		Env: os.Environ(),
		Sys: &syscall.SysProcAttr{},
		Files: []*os.File{
			os.Stdin,
			os.Stdout,
			os.Stderr,
		},
	}
	argv := make([]string, 4)
	argv[0] = "/usr/bin/tar"
	argv[1] = "--force-local"
	argv[2] = "-xf"
	argv[3] = tarFile
	process, err := os.StartProcess("/usr/bin/tar", argv, attr)
	if err != nil {
		return err
	}

	state, err := process.Wait()
	if err != nil {
		return err
	}

	if state.ExitCode() != 0 {
		return errors.New("解压出现异常:" + tarFile)
	}

	return nil
}
